package com.jueyue.dao.parse;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.jueyue.dao.parse.sqls.SqlFileBuilder;
import com.jueyue.dao.util.PublicUtil;

/**
 * 判断解析类型,并提供统一封装
 * 
 * @author JueYue
 * @date 2014年1月13日
 * @version 1.0
 */
public class ParseUtil {

	public static Map<String, String> getSQLS(InputStream ips) {
		return PublicUtil.getProperties("parseType").equalsIgnoreCase("SQLS") ? parseBySQLS(ips)
				: parseByXML(ips);
	}

	private static Map<String, String> parseByXML(InputStream ips) {
		Map<String, String> map = new HashMap<String, String>();
		Document document = null;
		SAXReader saxReader = new SAXReader();
		try {
			document = saxReader.read(ips);
			Element root = document.getRootElement();
			@SuppressWarnings("unchecked")
			List<Element> sqlElements = (List<Element>) root
					.selectNodes("//sqlElement");
			for (Element sql : sqlElements) {
				map.put(sql.attribute("key").getValue(), sql.getText());
			}
		} catch (DocumentException e) {
			throw new RuntimeException("---------读取sql语句XML文件出错:"
					+ e.getMessage());
		} finally {
			try {
				ips.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	private static Map<String, String> parseBySQLS(InputStream ips) {
		BufferedReader bufferedReader = new BufferedReader(
				new InputStreamReader(ips, Charset.forName("UTF-8")));
		try {
			SqlFileBuilder p = new SqlFileBuilder(bufferedReader);
			return p.map;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				ips.close();
				bufferedReader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
}
